import { computed, unref } from 'vue';
import { Locale as wotdLocale } from 'wot-design-uni';

// 引入英文语言包
import enUS from '@/locale/lang/en-US/wotdLocale';
import jaJP from '@/locale/lang/ja-JP/wotdLocale';
import zhCN from '@/locale/lang/zh-CN/wotdLocale';
import zhTW from '@/locale/lang/zh-TW/wotdLocale';
import { localeList } from '@/settings/localeSetting';
import { LocaleType } from '@/types/config';

import { i18n } from './setupI18n';

function setI18nLanguage(locale: LocaleType | string) {
  // 切换语言，下面两句缺一不可！！！
  const uniLocale = localeList.filter((o) => o.code === locale)[0]?.key;
  uni.setLocale(uniLocale ?? locale);
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale;
  } else {
    (i18n.global.locale as Recordable).value = locale;
  }
  // 设置 wot-design-uni 国际化
  setWotdLocale(locale);
}

/** 设置 wot-design-uni 国际化 */
function setWotdLocale(locale: LocaleType | string) {
  // 设置 wot-design-uni 国际化
  switch (locale) {
    case 'en':
    case 'en-US':
      wotdLocale.use('en-US', enUS);
      break;
    case 'ja':
    case 'ja-JP':
      wotdLocale.use('ja-JP', jaJP);
      break;
    case 'zh-Hans':
    case 'zh-CN':
      wotdLocale.use('zh-CN', zhCN);
      break;
    case 'zh-Hant':
    case 'zh-TW':
      wotdLocale.use('zh-TW', zhTW);
      break;
  }
}

export function useLocale() {
  const localInfo = computed(() => localeList.filter((o) => o.key === getLocale())[0]);

  function getLocale() {
    return uni.getLocale();
  }

  // Switching the language will change the locale of useI18n
  // And submit to configuration modification
  function changeLocale(locale: LocaleType) {
    const globalI18n = i18n.global;
    const currentLocale = unref(globalI18n.locale);
    if (currentLocale === locale) {
      return locale;
    }
    setI18nLanguage(locale);

    return locale;
  }

  setWotdLocale(getLocale());

  return {
    localInfo,
    getLocale,
    changeLocale,
  };
}
